package logic

import (
	"context"
	"github.com/thoas/go-funk"
	"learn-go/project/gozero/mall/pay/internal/platform"
	"learn-go/project/gozero/mall/pay/model"

	"learn-go/project/gozero/mall/pay/internal/svc"
	"learn-go/project/gozero/mall/pay/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPayCodeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetPayCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPayCodeLogic {
	return &GetPayCodeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetPayCodeLogic) GetPayCode(in *pb.PayCodeReq) (*pb.PayCodeRes, error) {
	tradeNo := GetTradeNo()
	platformServer := platform.NewPlatformServer()
	codeRes, err := platformServer.GetPayCode(&platform.GetPlatformCodeReq{
		Amount:     in.Amount,
		TradeNo:    tradeNo,
		Subject:    in.Subject,
		PlatformId: int32(in.Platform),
	})

	if err != nil {
		return nil, err
	}
	pay := model.OrderPay{
		OrderID:    in.OrderId,
		PayQrCode:  codeRes.PayUrl,
		TradeNo:    codeRes.TradeNo,
		PlatformID: int32(in.Platform),
		ExpireAt:   codeRes.ExpireAt,
	}
	err = l.svcCtx.DB.Debug().Create(&pay).Error
	if err != nil {
		return nil, err
	}

	return &pb.PayCodeRes{
		Data: &pb.PayCode{
			OrderId:  in.OrderId,
			PayUrl:   codeRes.PayUrl,
			ExpireAt: codeRes.ExpireAt,
			Status:   pb.PayStatus_PENDING,
		},
		Resp: &pb.Resp{
			Code: 1,
			Msg:  "success",
		},
	}, nil
}

func GetTradeNo() string {
	return funk.RandomString(12)
}
